//This test could retrieve my mobile's deposit balance and data usage balance.

package practice;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SaveUsageToFile {
	private WebDriver driver;
	private String baseUrl;
	private StringBuffer verificationErrors = new StringBuffer();
	@Before
	public void setUp() throws Exception {
		driver = new FirefoxDriver();
		baseUrl = "http://www.tpg.com.au/";
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	@Test
	public void testTPGUsage() throws Exception {
		driver.get(baseUrl + "/");
		driver.findElement(By.cssSelector("li.youract > a > div.yapobtn")).click();
		driver.findElement(By.name("check_username")).sendKeys("xiaoxli");
		
		
		driver.findElement(By.id("password1")).sendKeys("summer12");
	    
		
		driver.findElement(By.xpath("//div[2]/div[2]/input")).click();
		driver.findElement(By.linkText("View All Mobile Service Accounts")).click();
		
		
		driver.findElement(By.name("viewdetails|317030")).click();
		driver.findElement(By.linkText("Display charges for the period 2012-11-07 00:00:00 to 2012-12-06 23:59:59")).click();
		
		//System.out.println(driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/table[2]/tbody/tr/td[1]")).getText());
		
		//System.out.println(driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/p[28]")).getText());
		
		//Get deposit balance and remaining data
		String DepositBalance = driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/table[2]/tbody/tr/td[1]")).getText();
		String DataRemaining =  driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/p[28]")).getText();
		
		//Combine two strings to one string and split into string array 
		String[] DepositAndData = new StringBuilder().append(DepositBalance).append("\n").append(DataRemaining).toString().split("\n");
		
		int StringLength = DepositAndData.length;
		
		//Write to file
		
		FileWriter fWriter = null;
		BufferedWriter writer = null; 
		try {
		  fWriter = new FileWriter("c:\\tmp\\Usage.txt");
		  writer = new BufferedWriter(fWriter);
		  //WRITES 1 LINE TO FILE AND CHANGES LINE
		  for(int i=0; i<StringLength; i++) {
		  writer.write(DepositAndData[i]);
		  writer.newLine();
		  
		  }
		  writer.close();
		} catch (Exception e) {
		}
		
	}

	@After
	public void tearDown() throws Exception {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}

	private boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}
}
